<?php
include_once ROOT . '/utils/Notifier.php';
include_once ROOT . '/model/dao/UserDao.php';
$userDao = new UserDao();
array_walk_recursive($_POST, function (&$item, $key) {
    $item = addslashes($item);
});
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];
$email = $_POST['email'];
$pass1 = $_POST['password1'];
$pass2 = $_POST['password2'];

$error = '';
$options = array(
    'options' => array(
        'min_range' => 0,
        'max_range' => 110
    )
);
if (!empty($firstname) && preg_match("/^[a-zA-Z\s-]+$/i", $firstname) == 0) {
    $error .= 'Firstname must only contain characters<br/>';
}
if (!empty($lastname) && preg_match("/^[a-zA-Z\s-]+$/i", $lastname) == 0) {
    $error .= 'Lastname must only contain characters<br/>';
}
if (!empty($age) && filter_var($age, FILTER_VALIDATE_INT, $option) === FALSE) {
    $error .= 'Age must be between 0 and 110<br/>';
}
if (!empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
    $error .= 'Email isn\'t correct<br/>';
}
if (!empty($pass1) && $pass1 != $pass2) {
    $error .= 'Passwords doesn\'t match<br/>';
}
$user = $userDao->getByEmail($email);
if (!empty($user) && $user->getId() != $_SESSION['user']['id']) {
    $error .= 'This email already exist<br/>';
}
$user = $userDao->findById($_SESSION['user']['id']);
if (empty($user)) {
    $error .= 'Your account doesn\'t exist<br/>';
}

if (!empty($error)) {
    $notification = new Notifier('Update account error', $error);
    echo $template->render('user/inscription.php', array('titleInscr' => 'Update account',
        'route' => getRoute('updateuserpost'), 'buttonTxt' => 'Update', 'notifications' => array($notification)));
    die();
}
if (!empty($firstname)) {
    $user->setFirstname($firstname);
}
if (!empty($lastname)) {
    $user->setLastname($lastname);
}
if (!empty($age)) {
    $user->setAge($age);
}
if (!empty($email)) {
    $user->setEmail($email);
}
if (!empty($pass1)) {
    $user->setPassword($pass1);
}
$userDao->update($user);
$notification = new Notifier('Update account', 'Your account has been updated');
echo $template->render('static/welcome.php', array('notifications' => array($notification)));
$_SESSION['user']['id'] = $user->getId();
$_SESSION['user']['firstname'] = $user->getFirstname();
$_SESSION['user']['lastname'] = $user->getLastname();
$_SESSION['user']['email'] = $user->getEmail();
